#!/bin/bash

# API 测试脚本 - 用于测试应用接口并产生 SkyWalking Trace 数据

set -e

BASE_URL="http://localhost:8080"
REQUESTS_COUNT=10

echo "=========================================="
echo "API 测试脚本"
echo "=========================================="
echo "目标地址: ${BASE_URL}"
echo "测试次数: ${REQUESTS_COUNT}"
echo ""

# 检查应用是否启动
echo "检查应用状态..."
if ! curl -s -f "${BASE_URL}/api/health" > /dev/null; then
    echo "❌ 错误: 应用未启动或健康检查失败"
    echo "请先启动应用: ./scripts/run-with-skywalking.sh"
    exit 1
fi

echo "✅ 应用正常运行"
echo ""

# 测试用户接口
echo "=========================================="
echo "测试用户接口 (${REQUESTS_COUNT} 次请求)"
echo "=========================================="
for i in $(seq 1 $REQUESTS_COUNT); do
    echo -n "请求 $i: "
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "${BASE_URL}/api/users")
    if [ "$HTTP_CODE" == "200" ]; then
        echo "✅ 成功 (HTTP $HTTP_CODE)"
    else
        echo "❌ 失败 (HTTP $HTTP_CODE)"
    fi
    sleep 1
done

echo ""

# 测试订单接口
echo "=========================================="
echo "测试订单接口 (${REQUESTS_COUNT} 次请求)"
echo "=========================================="
for i in $(seq 1 $REQUESTS_COUNT); do
    echo -n "请求 $i: "
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "${BASE_URL}/api/orders")
    if [ "$HTTP_CODE" == "200" ]; then
        echo "✅ 成功 (HTTP $HTTP_CODE)"
    else
        echo "❌ 失败 (HTTP $HTTP_CODE)"
    fi
    sleep 1
done

echo ""
echo "=========================================="
echo "测试完成！"
echo "=========================================="
echo ""
echo "查看 SkyWalking UI: http://10.10.10.125:8088"
echo "查看 Swagger UI: ${BASE_URL}/swagger-ui.html"
echo ""
echo "提示: 等待 1-2 分钟后，在 SkyWalking UI 中可以看到："
echo "  - 服务: springboot-apm-demo"
echo "  - Endpoint: GET:/api/users, GET:/api/orders"
echo "  - Trace 数据和调用链"
echo ""

